package handlers

import (
	"gopkg.in/mgo.v2"
	"generalhandler/conf"
	"fmt"
	"gopkg.in/mgo.v2/bson"
	"encoding/json"
)

type StoreHandler struct {
	session *mgo.Session
}

func StoreHandlerInstance() *StoreHandler {
	instance := new(StoreHandler)
	err := instance.Session()
	if nil != err {
		panic(err)
	}
	return instance
}

func (sh *StoreHandler) Session() error {
	var err error
	sh.session, err =  mgo.Dial(conf.StoreConfigInstance().StoreAddress)
	if nil != err {
		return fmt.Errorf("failed to mgo.Dial, cuz %s", err.Error())
	}
	sh.session.SetMode(mgo.Monotonic, true)
	credential := &mgo.Credential{Username: conf.StoreConfigInstance().StoreUser,
		Password: conf.StoreConfigInstance().StorePwd}
	if err := sh.session.Login(credential); err != nil {
		return fmt.Errorf("failed to mgo.Login, cuz %s", err.Error())
	}
	return nil
}

func (sh *StoreHandler) Handle(bytesMsg []byte, log Logger, pub Publisher) error {

	var bsResult bson.M
	if err := json.Unmarshal(bytesMsg, &bsResult); nil != err {
		log.Error("failed to unmarshal msg %s, cuz %s", string(bytesMsg), err.Error())
		return nil
	}
	ifDomain, _ := bsResult["domain"]
	strDomain, _ := ifDomain.(string)
	if 0 == len(strDomain) {
		log.Warn("found no domain in %s", string(bytesMsg))
		return nil
	}

	ifTkId, _ := bsResult["tkid"]
	strTkId, _ := ifTkId.(string)
	if 0 == len(strTkId) {
		log.Warn("found no tkid in %s", string(bytesMsg))
		return nil
	}

	table := sh.session.Clone().DB(conf.StoreConfigInstance().StoreDB).C(conf.StoreConfigInstance().StoreTable)
	if err := table.Insert(bsResult); nil != err {
		if err = sh.Session(); nil != err {
			log.Error("failed to insert, cuz %s", string(bytesMsg), err.Error())
			return nil
		}
		if err = table.Insert(bsResult); nil != err {
			log.Error("failed to insert, cuz %s", string(bytesMsg), err.Error())
			return nil
		}
		return nil
	}

	return nil
}

